import Vue from 'vue';
import Router from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'
import auth from './utils/auth'

Vue.use(Router);

import Layout from './views/layout/Layout';

const Login = r=>require.ensure([],()=>r(require("./views/login/Index.vue")))
const NotFound = r=>require.ensure([],()=>r(require("./views/404/Index.vue")))
const Home = r=>require.ensure([],()=>r(require("./views/home/Index.vue")))
const Table = r=>require.ensure([],()=>r(require("./views/table/Index.vue")))
const Form = r=>require.ensure([],()=>r(require("./views/form/Index.vue")))
const FormOther = r=>require.ensure([],()=>r(require("./views/form/Other.vue")))

let asyncRouterMap=[
  {
    name: 'HomeParent',
    path: '/',
    redirect: '/home',
    component: Layout,
    children:[
      {path: '/home', name: 'Home', component: Home},
      {path: '/table', name: 'Table', component: Table, }
    ]
  },
  {
    name: 'TableParent',
    path: '/table',
    redirect: '/table/index',
    component: Layout,
    children:[
      {path: '/table/index', name: 'Table', component: Table}
    ],
  },
  {
    name: 'FormParent',
    path: '/form',
    component: Layout,
    redirect:'/form/index',
    children:[
      {path:'/form/index', component: Form, name:'Form'},
      {path:'/form/other', component: FormOther, name:'FormOther'},
    ]
  }
]

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/404',
      name: 'NotFound',
      component: NotFound,
    },
    ...asyncRouterMap,
    {
      path: '*',
      redirect: '/404',
    }
  ],
});

const noAuthRoutes = [
  'Login',
  'NotFound',
]

router.beforeEach((to, from, next) => {
  NProgress.start();
  let loggedIn = auth.getToken();
  if(to.name==='Login' && loggedIn){
    next({
      path:'/',
    })
    return;
  }
  if(noAuthRoutes.indexOf(to.name)<0 && !loggedIn){
    next({
      path:'/login',
      query:{
        redirect: to.fullPath
      }
    })
    return;
  }
  next();
});

router.afterEach(() => {
  NProgress.done();
});

export {asyncRouterMap};
export default router;
